//
//  LPFTabBar.swift
//  新浪微博
//
//  Created by mac on 16/4/16.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit

// 声明一个协议
protocol LPFTabBarDelegate: NSObjectProtocol{
    // 协议方法
    func composeButtonClick()
}

class LPFTabBar: UITabBar {

    // 声明一个代理 (声明一个代理需要用weak 修饰 方法循环引用  使用weak 修饰以后 必须 继承基协议 NSObjectProtocol
    weak var lpfDeletate: LPFTabBarDelegate?
    
    
    // MARK: - 监听方法 撰写按钮点击
    @objc private func composeButtonClick(){
        lpfDeletate?.composeButtonClick()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 设置控件
    func setupUI(){
        addSubview(composeButton)
    }
    
    // MARK: - 对子控件布局
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let width = SCREENW / 5
        //使用标示
        var index: CGFloat = 0
        
        // 遍历tabbar 身上的子控件
        for value in self.subviews{
            // 先判断他的子控件知否是我们的需要的UITabBarButton
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!){
                value.frame.origin.x = index * width
                value.frame.size.width = width
                
                index++
                
                if index == 2{
                    index++
                }
            }
        }
        composeButton.center.x = self.frame.width * 0.5
        composeButton.center.y = self.frame.height * 0.5
    }
    
    // MARK: - 撰写按钮
    private lazy var composeButton: UIButton = {
        let btn = UIButton()
        // 添加点击事件
        btn.addTarget(self, action: "composeButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        // 设置button 背景图片
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        // 设置image
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.sizeToFit()
        return btn
    }()
    
}
